package com.whfc.iot.mach.event;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.whfc.hdc.dto.AppDeviceCmdDTO;
import com.whfc.iot.mach.constant.MsgConst;
import com.whfc.iot.mach.entity.MachMsg0x8B;
import com.whfc.iot.mach.redis.MachCmdRedisDao;
import com.whfc.iot.session.Session;
import com.whfc.iot.session.SessionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Description: 设备上线事件后 - 指令发送监听器
 * @author: xugcheng
 * @version: 1.0
 * @date: 2019/8/23 14:49
 */
@Component
public class DeviceOnlineEventCmdListener implements ApplicationListener<DeviceOnlineEvent> {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SessionManager sessionManager;

    @Autowired
    private MachCmdRedisDao machCmdRedisDao;

    @Override
    @Async
    public void onApplicationEvent(DeviceOnlineEvent event) {
        try {
            Integer deviceId = event.getDeviceId();
            Integer deviceType = event.getDeviceType();
            //查询指令缓存
            AppDeviceCmdDTO cmdDTO = machCmdRedisDao.getCmd(deviceId);
            if (cmdDTO != null) {

                Integer cmd = cmdDTO.getCmd();
                String param = cmdDTO.getParam();
                logger.info("发送缓存指令,deviceId:{},cmd:{},param:{}", deviceId, cmdDTO.getCmd(), param);
                //发送指令
                JSONObject json = JSON.parseObject(param);
                Integer subCmd = json.getInteger(MsgConst.SUB_CMD);
                Double speed = json.getDouble(MsgConst.SPEED);

                MachMsg0x8B msg0x8B = new MachMsg0x8B();
                msg0x8B.setStartFlag(MsgConst.START_FLAG);
                msg0x8B.setDeviceType(deviceType);
                msg0x8B.setDeviceId(deviceId);
                msg0x8B.setSeq(MsgConst.DEFAULT_SEQ);
                msg0x8B.setSubCmd(subCmd);
                msg0x8B.setSpeed(speed != null ? speed : 0);

                //延迟发出数据
                TimeUnit.SECONDS.sleep(1);

                Session session = sessionManager.getSessionByDeviceId(deviceId);
                session.getChannel().writeAndFlush(msg0x8B);
            }

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
    }
}
